package ac.svn.accesscontrol.ui.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.swing.ListModel;
import javax.swing.event.ListDataListener;

import ac.svn.accesscontrol.store.ISVNItem;

public class ThreadedListModel implements ListModel 
{

	private ConcurrentLinkedQueue<ISVNItem> itemList;

	public ThreadedListModel()
	{
		itemList = new ConcurrentLinkedQueue<ISVNItem>();
	}

	@Override
	public Object getElementAt(int index) 
	{
		Object[] listAsArray = itemList.toArray();
		if(null != listAsArray)
		{
			return listAsArray[index];
		}
		else
		{
			return null;
		}
	}

	/***
	 * Method returns number of items in the Model.
	 */
	@Override
	public int getSize() 
	{
		return itemList.size();
	}

	/***
	 *  Method adds specified item to list model.
	 *  Item can be duplicated in list model using this method. 
	 * @param item
	 */
	public void addElement(ISVNItem item)
	{
		itemList.add(item);
	}

	/***
	 * Method ensures item added will not duplicate in target list view.
	 * @param item
	 */
	public boolean addElementOnce(ISVNItem item)
	{
		if(false == itemList.contains(item))
		{
			itemList.add(item);
			return true;
		}
		return false;
	}

	/***
	 * Method adds set of distinct items in the list model without clearing previously added elements.
	 * @param items
	 */
	public void addElement(Set<ISVNItem> items)
	{
		for(ISVNItem item:items)
		{
			itemList.add(item);
		}
	}

	/***
	 * Method clears the items currently held by Model.
	 */
	public void clear()
	{
		itemList.clear();
	}

	/***
	 * Method removes specified element from the Model.
	 * @param item
	 */
	public void removeItem(ISVNItem item)
	{
		itemList.remove(item);
	}

	/***
	 * 	Method returns a list of all items present in list model.
	 * @return
	 */
	public List<ISVNItem> getItems()
	{
		List<ISVNItem> itemsSet = new ArrayList<ISVNItem>();
		for(Object isvnItem  : itemList.toArray())
		{
			itemsSet.add((ISVNItem) isvnItem);
		}
		return itemsSet;
	}


	@Override
	public void removeListDataListener(ListDataListener arg0) 
	{
	}
	@Override
	public void addListDataListener(ListDataListener arg0) 
	{
	}

}
